<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <title>学生教师管理系统</title>
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

    <!-- 自定义配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        secondary: '#10B981',
                        danger: '#EF4444',
                        warning: '#F59E0B',
                        info: '#6366F1',
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>

    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }

            .card-shadow {
                box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
            }
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen flex flex-col">
<!-- 导航栏 -->

<nav class="bg-white shadow-md">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex justify-between h-16">
            <div class="flex items-center">
                <a class="flex-shrink-0 flex items-center" href="#">
                    <i class="fa fa-graduation-cap text-primary text-2xl mr-2"></i>
                    <span class="font-bold text-xl">学生教师管理系统</span>
                </a>
            </div>
            <div class="flex items-center space-x-4">
                <button class="px-4 py-2 text-gray-500 font-medium hover:text-gray-700" id="classesTab">
                    <i class="fa fa-building mr-1"></i> 班级管理
                </button>
                <button class="px-4 py-2 text-primary font-medium border-b-2 border-primary" id="studentsTab">
                    <i class="fa fa-users mr-1"></i> 学生管理
                </button>
                <button class="px-4 py-2 text-gray-500 font-medium hover:text-gray-700" id="teachersTab">
                    <i class="fa fa-briefcase mr-1"></i> 教师管理
                </button>
                <button class="px-4 py-2 text-danger font-medium hover:text-danger/90" id="logoutBtn">
                    <i class="fa fa-sign-out mr-1"></i> 退出登录
                </button>
            </div>
        </div>
    </div>
</nav>

<!-- 班级管理 (默认隐藏) -->
<div class="hidden" id="classesSection">
    <div class="bg-white rounded-lg shadow-lg overflow-hidden mb-8">
        <div class="bg-info p-4">
            <h2 class="text-white text-xl font-bold flex items-center">
                <i class="fa fa-building mr-2"></i> 班级列表
                <button class="ml-auto bg-white text-info px-4 py-1 rounded-md text-sm font-medium hover:bg-gray-100 transition-colors"
                        id="addClassBtn">
                    <i class="fa fa-plus mr-1"></i> 添加班级
                </button>
            </h2>
        </div>
        <div class="p-4">
            <div class="flex justify-between mb-4">
                <div class="relative">
                        <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-500">
                            <i class="fa fa-search"></i>
                        </span>
                    <input class="pl-10 block w-full rounded-md border-gray-300 shadow-sm focus:border-info focus:ring focus:ring-info/30 transition duration-200" id="classSearch" placeholder="搜索班级..."
                           type="text">
                </div>
                <button class="bg-gray-100 hover:bg-gray-200 text-gray-700 px-4 py-1 rounded-md text-sm font-medium transition-colors"
                        id="refreshClasses">
                    <i class="fa fa-refresh mr-1"></i> 刷新
                </button>
            </div>
            <div class="overflow-x-auto" id="classesTable">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
                            scope="col">班级
                            ID
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
                            scope="col">班级名称
                        </th>
                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider"
                            scope="col">操作
                        </th>
                    </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200" id="classesBody">
                    <!-- 班级数据将通过 JavaScript 动态填充 -->
                    <tr class="text-center">
                        <td class="px-6 py-12 text-gray-500" colspan="3">
                            <i class="fa fa-spinner fa-spin text-2xl mb-2"></i>
                            <p>加载中...</p>
                        </td>
                    </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- 添加班级模态框（假设这里简单模拟，你可按需完善） -->
<div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden" id="addClassModal">
    <div class="bg-white rounded-lg shadow-xl w-full max-w-md transform transition-all">
        <div class="bg-info p-4 rounded-t-lg">
            <h3 class="text-white text-lg font-bold flex items-center">
                <i class="fa fa-plus mr-2"></i> 添加班级
                <button class="ml-auto text-white hover:text-gray-200" id="closeClassModal">
                    <i class="fa fa-times"></i>
                </button>
            </h3>
        </div>
        <div class="p-6">
            <form id="addClassForm">
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-1" for="classId">班级 ID</label>
                    <input class="block w-full rounded-md border-gray-300 shadow-sm focus:border-info focus:ring focus:ring-info/30 transition duration-200" id="classId"
                           required
                           type="text">
                </div>
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-1" for="className">班级名称</label>
                    <input class="block w-full rounded-md border-gray-300 shadow-sm focus:border-info focus:ring focus:ring-info/30 transition duration-200" id="className"
                           required
                           type="text">
                </div>
                <div class="flex justify-end space-x-4">
                    <button class="px-4 py-2 bg-gray-200 text-gray-800 rounded-md hover:bg-gray-300 transition-colors" id="cancelAddClass"
                            type="button">
                        取消
                    </button>
                    <button class="px-4 py-2 bg-info text-white rounded-md hover:bg-info/90 transition-colors"
                            type="submit">保存
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 编辑班级模态框 -->
<div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden" id="editClassModal">
    <div class="bg-white rounded-lg shadow-xl w-full max-w-md transform transition-all">
        <div class="bg-info p-4 rounded-t-lg">
            <h3 class="text-white text-lg font-bold flex items-center">
                <i class="fa fa-pencil mr-2"></i> 编辑班级
                <button class="ml-auto text-white hover:text-gray-200" id="closeEditClassModal">
                    <i class="fa fa-times"></i>
                </button>
            </h3>
        </div>
        <div class="p-6">
            <form id="editClassForm">
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-1" for="editClassId">班级 ID</label>
                    <input class="block w-full rounded-md border-gray-300 shadow-sm focus:border-info focus:ring focus:ring-info/30 transition duration-200" id="editClassId"
                           readonly
                           type="text">
                </div>
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-1" for="editClassName">班级名称</label>
                    <input class="block w-full rounded-md border-gray-300 shadow-sm focus:border-info focus:ring focus:ring-info/30 transition duration-200" id="editClassName"
                           required
                           type="text">
                </div>
                <div class="flex justify-end space-x-4">
                    <button class="px-4 py-2 bg-gray-200 text-gray-800 rounded-md hover:bg-gray-300 transition-colors" id="cancelEditClass"
                            type="button">
                        取消
                    </button>
                    <button class="px-4 py-2 bg-info text-white rounded-md hover:bg-info/90 transition-colors"
                            type="submit">保存
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', () => {
        // 模拟班级数据
        let originalClasses = [];

// 在DOMContentLoaded事件中，添加事件委托
        document.getElementById('classesBody').addEventListener('click', (e) => {
            const target = e.target.closest('button');
            if (!target) return;

            const row = target.closest('tr');
            const classId = row.cells[0].textContent;
            const className = row.cells[1].textContent; // 从表格单元格取名称

            if (target.classList.contains('edit-btn')) {
                editClass(classId, className); // 传两个参数
            } else if (target.classList.contains('delete-btn')) {
                confirmDeleteClass(classId, className);
            }
        });

        // 初始化添加班级按钮点击事件
        document.getElementById('addClassBtn').addEventListener('click', () => {
            document.getElementById('addClassModal').classList.remove('hidden');
            document.getElementById('addClassForm').reset();
        });

        // 初始化关闭添加班级模态框按钮
        document.getElementById('closeClassModal').addEventListener('click', () => {
            document.getElementById('addClassModal').classList.add('hidden');
        });

        // 初始化取消添加班级按钮
        document.getElementById('cancelAddClass').addEventListener('click', () => {
            document.getElementById('addClassModal').classList.add('hidden');
        });

        // 初始化添加班级表单提交事件
        document.getElementById('addClassForm').addEventListener('submit', (e) => {
            e.preventDefault();
            const id = document.getElementById('classId').value;
            const name = document.getElementById('className').value;

            // 1. 前端校验（可选，增强用户体验）
            if (!id || !name) {
                showNotification('error', '错误', '班级ID和名称不能为空');
                return;
            }

            // 2. 禁用按钮，防止重复提交
            const submitButton = e.target.querySelector('button[type="submit"]');
            submitButton.disabled = true;
            submitButton.textContent = '正在提交...';

            fetch('/api/classes', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({id, name})
            })
                .then(response => {
                    if (response.ok) {
                        return response.json();
                    } else {
                        return response.json().then(errorData => {
                            throw new Error(errorData.error || `HTTP错误 ${response.status}`);
                        });
                    }
                })
                // 修改添加班级的成功回调
                .then(data => {
                    showNotification('success', '成功', '班级添加成功');
                    originalClasses.push(data);
                    loadClasses();

                    // 关闭模态框
                    const modal = document.getElementById('addClassModal');
                    if (modal) modal.classList.add('hidden');
                })

                .catch(error => {
                    showNotification('error', '失败', error.message);
                })
                .finally(() => {
                    submitButton.disabled = false;
                    submitButton.textContent = '添加班级';
                    e.target.reset();
                });
        });

        // 假设存在编辑表单提交事件
        document.getElementById('editClassForm').addEventListener('submit', (e) => {
            e.preventDefault();
            const id = document.getElementById('editClassId').value;
            const name = document.getElementById('editClassName').value;

            const updatedClass = {id, name};
            console.log('Updating class:', updatedClass);

            fetch(`/api/classes`, {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(newClass)
            })
                .then(response => {
                    // 新增：打印完整响应状态码
                    console.log('添加班级响应状态码:', response.status);
                    // 严格判断状态码是否为 201（创建成功）
                    if (response.status === 201) {
                        return response.json(); // 解析成功响应
                    } else {
                        throw new Error(`请求失败，状态码: ${response.status}`); // 抛出异常以触发失败提示
                    }
                })
                // 在addClassForm提交事件中，确保数据立即更新
                .then(data => {
                    showNotification('success', '成功', '班级添加成功');
                    originalClasses.push(data); // 手动添加到数组
                    loadClasses(); // 重新加载视图
                    document.getElementById('addClassModal').classList.add('hidden');
                })
                .catch(error => {
                    showNotification('error', '失败', '班级添加失败: ' + error.message);
                    console.error('添加班级失败:', error);
                });
        });


        // 初始化刷新按钮
        document.getElementById('refreshClasses').addEventListener('click', loadClasses);

        // 加载班级数据
        function loadClasses() {
            const classesBody = document.getElementById('classesBody');
            classesBody.innerHTML = `
        <tr class="text-center">
            <td colspan="3" class="px-6 py-12 text-gray-500">
                <i class="fa fa-spinner fa-spin text-2xl mb-2"></i>
                <p>加载中...</p>
            </td>
        </tr>
    `;

            fetch('/api/classes')
                .then(response => {
                    console.log('Response status:', response.status);
                    console.log('Response headers:', response.headers);
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    console.log('Received data:', data);
                    originalClasses = data;
                    classesBody.innerHTML = '';
// 在loadClasses函数中，移除内联onclick事件
                    data.forEach(classInfo => {
                        const row = document.createElement('tr');
                        row.innerHTML = `
            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${classInfo.id}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${classInfo.name}</td>
            <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                <button onclick="editClass('${classInfo.id}', '${classInfo.name}')" class="text-indigo-600 hover:text-indigo-900 mr-3">
                    <i class="fa fa-pencil"></i> 编辑
                </button>
                <button onclick="confirmDeleteClass('${classInfo.id}', '${classInfo.name}')" class="text-red-600 hover:text-red-900">
                    <i class="fa fa-trash"></i> 删除
                </button>
            </td>
        `;
                        classesBody.appendChild(row);
                    });
                })
                .catch(error => {
                    console.error('Error loading classes:', error);
                    classesBody.innerHTML = `
                <tr class="text-center">
                    <td colspan="3" class="px-6 py-12 text-gray-500">
                        <i class="fa fa-exclamation-triangle text-2xl mb-2"></i>
                        <p>加载班级数据失败: ${error.message}</p>
                    </td>
                </tr>
            `;
                });
        }

        // 初始加载班级数据
        loadClasses();
    });
</script>
</body>
</html>

<!-- 主要内容 -->
<main class="flex-grow container mx-auto px-4 py-8">
    <!-- 学生管理 -->
    <div class="hidden" id="studentsSection"> <!-- 添加 hidden 类 -->
        <!--        class="hidden"是首页显示的意思      -->
        <div class="bg-white rounded-lg shadow-lg overflow-hidden mb-8">
            <div class="bg-primary p-4">
                <h2 class="text-white text-xl font-bold flex items-center">
                    <i class="fa fa-users mr-2"></i> 学生列表
                    <button class="ml-auto bg-white text-primary px-4 py-1 rounded-md text-sm font-medium hover:bg-gray-100 transition-colors"
                            id="addStudentBtn">
                        <i class="fa fa-plus mr-1"></i> 添加学生
                    </button>
                </h2>
            </div>
            <div class="p-4">
                <div class="flex justify-between mb-4">
                    <div class="relative">
                            <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-500">
                                <i class="fa fa-search"></i>
                            </span>
                        <input class="pl-10 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary/30 transition duration-200" id="studentSearch" placeholder="搜索学生..."
                               type="text">
                    </div>
                    <button class="bg-gray-100 hover:bg-gray-200 text-gray-700 px-4 py-1 rounded-md text-sm font-medium transition-colors"
                            id="refreshStudents">
                        <i class="fa fa-refresh mr-1"></i> 刷新
                    </button>
                </div>
                <div class="overflow-x-auto" id="studentsTable">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
                                scope="col">
                                学号
                            </th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
                                scope="col">
                                姓名
                            </th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
                                scope="col">
                                年龄
                            </th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
                                scope="col">
                                性别
                            </th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
                                scope="col">
                                成绩
                            </th>
                            <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider"
                                scope="col">
                                操作
                            </th>
                        </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200" id="studentsBody">
                        <!-- 学生数据将通过 JavaScript 动态填充 -->
                        <tr class="text-center">
                            <td class="px-6 py-12 text-gray-500" colspan="6">
                                <i class="fa fa-spinner fa-spin text-2xl mb-2"></i>
                                <p>加载中...</p>
                            </td>
                        </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- 教师管理 (默认隐藏) -->
    <div class="hidden" id="teachersSection">
        <div class="bg-white rounded-lg shadow-lg overflow-hidden mb-8">
            <div class="bg-secondary p-4">
                <h2 class="text-white text-xl font-bold flex items-center">
                    <i class="fa fa-briefcase mr-2"></i> 教师列表
                    <button class="ml-auto bg-white text-secondary px-4 py-1 rounded-md text-sm font-medium hover:bg-gray-100 transition-colors"
                            id="addTeacherBtn">
                        <i class="fa fa-plus mr-1"></i> 添加教师
                    </button>
                </h2>
            </div>
            <div class="p-4">
                <div class="flex justify-between mb-4">
                    <div class="relative">
                            <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-500">
                                <i class="fa fa-search"></i>
                            </span>
                        <input class="pl-10 block w-full rounded-md border-gray-300 shadow-sm focus:border-secondary focus:ring focus:ring-secondary/30 transition duration-200" id="teacherSearch" placeholder="搜索教师..."
                               type="text">
                    </div>
                    <button class="bg-gray-100 hover:bg-gray-200 text-gray-700 px-4 py-1 rounded-md text-sm font-medium transition-colors"
                            id="refreshTeachers">
                        <i class="fa fa-refresh mr-1"></i> 刷新
                    </button>
                </div>
                <div class="overflow-x-auto" id="teachersTable">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
                                scope="col">
                                教工号
                            </th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
                                scope="col">
                                姓名
                            </th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
                                scope="col">
                                年龄
                            </th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
                                scope="col">
                                性别
                            </th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
                                scope="col">
                                教学内容
                            </th>
                            <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider"
                                scope="col">
                                操作
                            </th>
                        </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200" id="teachersBody">
                        <!-- 教师数据将通过 JavaScript 动态填充 -->
                        <tr class="text-center">
                            <td class="px-6 py-12 text-gray-500" colspan="6">
                                <i class="fa fa-spinner fa-spin text-2xl mb-2"></i>
                                <p>加载中...</p>
                            </td>
                        </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</main>

<!-- 页脚 -->
<footer class="bg-gray-800 text-white py-6">
    <div class="container mx-auto px-4">
        <div class="text-center">
            <p>© 2025 学生教师管理系统 | 版权所有</p>
        </div>
    </div>
</footer>
<script>
    document.addEventListener('DOMContentLoaded', () => {
        // 初始化选项卡切换等原有逻辑保持不变

        // 处理退出按钮点击事件
        document.getElementById('logoutBtn').addEventListener('click', () => {
            // 清除本地存储的登录信息（如果有）
            localStorage.removeItem('isLoggedIn');
            // 跳转到登录页面
            window.location.href = 'login.html';
        });
    });
</script>
</body>
</html>

<!-- 添加学生模态框 -->
<div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden" id="addStudentModal">
    <div class="bg-white rounded-lg shadow-xl w-full max-w-md transform transition-all">
        <div class="bg-primary p-4 rounded-t-lg">
            <h3 class="text-white text-lg font-bold flex items-center">
                <i class="fa fa-user-plus mr-2"></i> 添加学生
                <button class="ml-auto text-white hover:text-gray-200" id="closeStudentModal">
                    <i class="fa fa-times"></i>
                </button>
            </h3>
        </div>
        <div class="p-6">
            <form id="addStudentForm">
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-1" for="studentId">学号</label>
                    <input class="block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary/30 transition duration-200" id="studentId"
                           required
                           type="text">
                </div>
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-1" for="studentName">姓名</label>
                    <input class="block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary/30 transition duration-200" id="studentName"
                           required
                           type="text">
                </div>
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-1" for="studentAge">年龄</label>
                    <input class="block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary/30 transition duration-200" id="studentAge"
                           required
                           type="number">
                </div>
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-1" for="studentSex">性别</label>
                    <select class="block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary/30 transition duration-200"
                            id="studentSex"
                            required>
                        <option value="男">男</option>
                        <option value="女">女</option>
                    </select>
                </div>
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 mb-1" for="studentGrade">成绩</label>
                    <input class="block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary/30 transition duration-200" id="studentGrade" required
                           step="0.01"
                           type="number">
                </div>
                <div class="flex justify-end space-x-4">
                    <button class="px-4 py-2 bg-gray-200 text-gray-800 rounded-md hover:bg-gray-300 transition-colors" id="cancelAddStudent"
                            type="button">
                        取消
                    </button>
                    <button class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90 transition-colors"
                            type="submit">保存
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 添加教师模态框 -->
<div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden" id="addTeacherModal">
    <div class="bg-white rounded-lg shadow-xl w-full max-w-md transform transition-all">
        <div class="bg-secondary p-4 rounded-t-lg">
            <h3 class="text-white text-lg font-bold flex items-center">
                <i class="fa fa-user-plus mr-2"></i> 添加教师
                <button class="ml-auto text-white hover:text-gray-200" id="closeTeacherModal">
                    <i class="fa fa-times"></i>
                </button>
            </h3>
        </div>
        <div class="p-6">
            <form id="addTeacherForm">
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-1" for="teacherId">教工号</label>
                    <input class="block w-full rounded-md border-gray-300 shadow-sm focus:border-secondary focus:ring focus:ring-secondary/30 transition duration-200" id="teacherId"
                           required
                           type="text">
                </div>
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-1" for="teacherName">姓名</label>
                    <input class="block w-full rounded-md border-gray-300 shadow-sm focus:border-secondary focus:ring focus:ring-secondary/30 transition duration-200" id="teacherName"
                           required
                           type="text">
                </div>
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-1" for="teacherAge">年龄</label>
                    <input class="block w-full rounded-md border-gray-300 shadow-sm focus:border-secondary focus:ring focus:ring-secondary/30 transition duration-200" id="teacherAge"
                           required
                           type="number">
                </div>
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-1" for="teacherSex">性别</label>
                    <select class="block w-full rounded-md border-gray-300 shadow-sm focus:border-secondary focus:ring focus:ring-secondary/30 transition duration-200"
                            id="teacherSex"
                            required>
                        <option value="男">男</option>
                        <option value="女">女</option>
                    </select>
                </div>
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 mb-1" for="teacherTeaching">教学内容</label>
                    <input class="block w-full rounded-md border-gray-300 shadow-sm focus:border-secondary focus:ring focus:ring-secondary/30 transition duration-200" id="teacherTeaching"
                           required
                           type="text">
                </div>
                <div class="flex justify-end space-x-4">
                    <button class="px-4 py-2 bg-gray-200 text-gray-800 rounded-md hover:bg-gray-300 transition-colors" id="cancelAddTeacher"
                            type="button">
                        取消
                    </button>
                    <button class="px-4 py-2 bg-secondary text-white rounded-md hover:bg-secondary/90 transition-colors"
                            type="submit">
                        保存
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 编辑学生模态框 -->
<div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden" id="editStudentModal">
    <div class="bg-white rounded-lg shadow-xl w-full max-w-md transform transition-all">
        <div class="bg-warning p-4 rounded-t-lg">
            <h3 class="text-white text-lg font-bold flex items-center">
                <i class="fa fa-pencil mr-2"></i> 编辑学生
                <button class="ml-auto text-white hover:text-gray-200" id="closeEditStudentModal">
                    <i class="fa fa-times"></i>
                </button>
            </h3>
        </div>
        <div class="p-6">
            <form id="editStudentForm">
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-1" for="editStudentId">学号</label>
                    <input class="block w-full rounded-md border-gray-300 shadow-sm focus:border-warning focus:ring focus:ring-warning/30 transition duration-200" id="editStudentId"
                           readonly
                           type="text">
                </div>
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-1" for="editStudentName">姓名</label>
                    <input class="block w-full rounded-md border-gray-300 shadow-sm focus:border-warning focus:ring focus:ring-warning/30 transition duration-200" id="editStudentName"
                           required
                           type="text">
                </div>
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-1" for="editStudentAge">年龄</label>
                    <input class="block w-full rounded-md border-gray-300 shadow-sm focus:border-warning focus:ring focus:ring-warning/30 transition duration-200" id="editStudentAge"
                           required
                           type="number">
                </div>
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-1" for="editStudentSex">性别</label>
                    <select class="block w-full rounded-md border-gray-300 shadow-sm focus:border-warning focus:ring focus:ring-warning/30 transition duration-200"
                            id="editStudentSex"
                            required>
                        <option value="男">男</option>
                        <option value="女">女</option>
                    </select>
                </div>
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 mb-1" for="editStudentGrade">成绩</label>
                    <input class="block w-full rounded-md border-gray-300 shadow-sm focus:border-warning focus:ring focus:ring-warning/30 transition duration-200" id="editStudentGrade" required
                           step="0.01"
                           type="number">
                </div>
                <div class="flex justify-end space-x-4">
                    <button class="px-4 py-2 bg-gray-200 text-gray-800 rounded-md hover:bg-gray-300 transition-colors" id="cancelEditStudent"
                            type="button">
                        取消
                    </button>
                    <button class="px-4 py-2 bg-warning text-white rounded-md hover:bg-warning/90 transition-colors"
                            type="submit">保存
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 编辑教师模态框 -->
<div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden" id="editTeacherModal">
    <div class="bg-white rounded-lg shadow-xl w-full max-w-md transform transition-all">
        <div class="bg-info p-4 rounded-t-lg">
            <h3 class="text-white text-lg font-bold flex items-center">
                <i class="fa fa-pencil mr-2"></i> 编辑教师
                <button class="ml-auto text-white hover:text-gray-200" id="closeEditTeacherModal">
                    <i class="fa fa-times"></i>
                </button>
            </h3>
        </div>
        <div class="p-6">
            <form id="editTeacherForm">
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-1" for="editTeacherId">教工号</label>
                    <input class="block w-full rounded-md border-gray-300 shadow-sm focus:border-info focus:ring focus:ring-info/30 transition duration-200" id="editTeacherId"
                           readonly
                           type="text">
                </div>
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-1" for="editTeacherName">姓名</label>
                    <input class="block w-full rounded-md border-gray-300 shadow-sm focus:border-info focus:ring focus:ring-info/30 transition duration-200" id="editTeacherName"
                           required
                           type="text">
                </div>
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-1" for="editTeacherAge">年龄</label>
                    <input class="block w-full rounded-md border-gray-300 shadow-sm focus:border-info focus:ring focus:ring-info/30 transition duration-200" id="editTeacherAge"
                           required
                           type="number">
                </div>
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-1" for="editTeacherSex">性别</label>
                    <select class="block w-full rounded-md border-gray-300 shadow-sm focus:border-info focus:ring focus:ring-info/30 transition duration-200"
                            id="editTeacherSex"
                            required>
                        <option value="男">男</option>
                        <option value="女">女</option>
                    </select>
                </div>
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 mb-1"
                           for="editTeacherTeaching">教学内容</label>
                    <input class="block w-full rounded-md border-gray-300 shadow-sm focus:border-info focus:ring focus:ring-info/30 transition duration-200" id="editTeacherTeaching"
                           required
                           type="text">
                </div>
                <div class="flex justify-end space-x-4">
                    <button class="px-4 py-2 bg-gray-200 text-gray-800 rounded-md hover:bg-gray-300 transition-colors" id="cancelEditTeacher"
                            type="button">
                        取消
                    </button>
                    <button class="px-4 py-2 bg-info text-white rounded-md hover:bg-info/90 transition-colors"
                            type="submit">保存
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 确认删除模态框 -->
<div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden" id="confirmDeleteModal">
    <div class="bg-white rounded-lg shadow-xl w-full max-w-md transform transition-all">
        <div class="bg-danger p-4 rounded-t-lg">
            <h3 class="text-white text-lg font-bold flex items-center">
                <i class="fa fa-trash mr-2"></i> 确认删除
            </h3>
        </div>
        <div class="p-6">
            <p class="text-gray-700 mb-6" id="deleteMessage">你确定要删除此记录吗？此操作不可撤销。</p>
            <div class="flex justify-end space-x-4">
                <button class="px-4 py-2 bg-gray-200 text-gray-800 rounded-md hover:bg-gray-300 transition-colors" id="cancelDelete"
                        type="button">取消
                </button>
                <button class="px-4 py-2 bg-danger text-white rounded-md hover:bg-danger/90 transition-colors" id="confirmDelete"
                        type="button">确认删除
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 通知提示 -->
<div class="fixed top-4 right-4 max-w-xs bg-white rounded-lg shadow-lg overflow-hidden transform translate-x-full transition-transform duration-500 z-50"
     id="notification"
     style="right: -100%;">
    <div class="p-3 bg-primary text-white flex justify-between items-center" id="notificationHeader">
        <h3 class="font-medium" id="notificationTitle">通知</h3>
        <button class="text-white hover:text-gray-200 transition-colors" id="closeNotification">
            <i class="fa fa-times"></i>
        </button>
    </div>
    <div class="p-4">
        <p id="notificationMessage"></p>
    </div>
</div>

<script>
    // 模拟数据 - 学生
    const mockStudents = [
        {id: '2025001', name: '张三', age: 20, sex: '男', grade: 85.5},
        {id: '2025002', name: '李四', age: 21, sex: '女', grade: 90.0},
        {id: '2025003', name: '王五', age: 19, sex: '男', grade: 78.2},
        {id: '2025004', name: '赵六', age: 22, sex: '女', grade: 92.8},
        {id: '2025005', name: '钱七', age: 20, sex: '男', grade: 88.7},
    ];

    // 模拟数据 - 教师
    const mockTeachers = [
        {id: 'T2025001', name: '周老师', age: 35, sex: '女', teaching: '数学'},
        {id: 'T2025002', name: '吴老师', age: 42, sex: '男', teaching: '语文'},
        {id: 'T2025003', name: '郑老师', age: 38, sex: '女', teaching: '英语'},
        {id: 'T2025004', name: '王老师', age: 30, sex: '男', teaching: '物理'},
        {id: 'T2025005', name: '孙老师', age: 45, sex: '女', teaching: '化学'},
    ];

    /// 当前选中的学生/教师 ID（用于编辑和删除）
    let currentStudentId = null;
    let currentTeacherId = null;
    let currentEntityType = null; // 'student' 或 'teacher'
    let originalStudents = [];
    let originalTeachers = [];

    // DOM 加载完成后执行
    document.addEventListener('DOMContentLoaded', () => {
        // 确保通知提示框初始为隐藏状态
        const notification = document.getElementById('notification');
        notification.classList.add('translate-x-full');
        notification.style.right = '-100%';

        // 初始化选项卡切换


        document.getElementById('studentsTab').addEventListener('click', () => {
            // 隐藏所有模块
            document.getElementById('classesSection').classList.add('hidden'); // 隐藏班级模块
            document.getElementById('teachersSection').classList.add('hidden'); // 隐藏教师模块
            // 显示学生模块并更新样式
            document.getElementById('studentsTab').classList.add('text-primary', 'border-b-2', 'border-primary');
            document.getElementById('studentsTab').classList.remove('text-gray-500');
            document.getElementById('studentsSection').classList.remove('hidden');
            loadStudents();
        });

        document.getElementById('teachersTab').addEventListener('click', () => {
            // 隐藏所有模块
            document.getElementById('classesSection').classList.add('hidden'); // 隐藏班级模块
            document.getElementById('studentsSection').classList.add('hidden'); // 隐藏学生模块
            // 显示教师模块并更新样式
            document.getElementById('teachersTab').classList.add('text-secondary', 'border-b-2', 'border-secondary');
            document.getElementById('teachersTab').classList.remove('text-gray-500');
            document.getElementById('teachersSection').classList.remove('hidden');
            loadTeachers();
        });

        // 初始化模态框事件
        document.getElementById('addStudentBtn').addEventListener('click', () => {
            document.getElementById('addStudentModal').classList.remove('hidden');
            document.getElementById('addStudentForm').reset();
        });

        document.getElementById('closeStudentModal').addEventListener('click', () => {
            document.getElementById('addStudentModal').classList.add('hidden');
        });

        document.getElementById('cancelAddStudent').addEventListener('click', () => {
            document.getElementById('addStudentModal').classList.add('hidden');
        });

        document.getElementById('addTeacherBtn').addEventListener('click', () => {
            document.getElementById('addTeacherModal').classList.remove('hidden');
            document.getElementById('addTeacherForm').reset();
        });

        document.getElementById('closeTeacherModal').addEventListener('click', () => {
            document.getElementById('addTeacherModal').classList.add('hidden');
        });

        document.getElementById('cancelAddTeacher').addEventListener('click', () => {
            document.getElementById('addTeacherModal').classList.add('hidden');
        });

        document.getElementById('closeEditStudentModal').addEventListener('click', () => {
            document.getElementById('editStudentModal').classList.add('hidden');
        });

        document.getElementById('cancelEditStudent').addEventListener('click', () => {
            document.getElementById('editStudentModal').classList.add('hidden');
        });

        document.getElementById('closeEditTeacherModal').addEventListener('click', () => {
            document.getElementById('editTeacherModal').classList.add('hidden');
        });

        document.getElementById('cancelEditTeacher').addEventListener('click', () => {
            document.getElementById('editTeacherModal').classList.add('hidden');
        });

        document.getElementById('confirmDelete').addEventListener('click', () => {
            if (currentEntityType === 'class') {
                deleteClass();
            }
            document.getElementById('confirmDeleteModal').classList.add('hidden');
        });

        document.getElementById('closeNotification').addEventListener('click', () => {
            notification.classList.add('translate-x-full');
        });

        // 初始化表单提交事件
        document.getElementById('addStudentForm').addEventListener('submit', (e) => {
            e.preventDefault();
            addStudent();
        });

        document.getElementById('addTeacherForm').addEventListener('submit', (e) => {
            e.preventDefault();
            addTeacher();
        });

        document.getElementById('editStudentForm').addEventListener('submit', (e) => {
            e.preventDefault();
            updateStudent();
        });

        document.getElementById('editTeacherForm').addEventListener('submit', (e) => {
            e.preventDefault();
            updateTeacher();
        });

        document.getElementById('confirmDelete').addEventListener('click', () => {
            if (currentEntityType === 'class') {
                deleteClass();
            } else if (currentEntityType === 'student') {
                deleteStudent();
            } else if (currentEntityType === 'teacher') {
                deleteTeacher();
            }
            document.getElementById('confirmDeleteModal').classList.add('hidden');
            resetDeleteState(); // 重置删除状态
        });
        // 取消删除按钮事件（新增）
        document.getElementById('cancelDelete').addEventListener('click', () => {
            document.getElementById('confirmDeleteModal').classList.add('hidden');
            resetDeleteState(); // 重置删除状态
        });

        // 重置删除相关状态（新增）
        function resetDeleteState() {
            currentEntityType = null;
            currentStudentId = null;
            currentTeacherId = null;
            // 如果有班级ID变量，也需要重置
            // currentClassId = null;
        }

        // 初始化刷新按钮
        document.getElementById('refreshStudents').addEventListener('click', loadStudents);
        document.getElementById('refreshTeachers').addEventListener('click', loadTeachers);

        // 初始化搜索功能
        document.getElementById('studentSearch').addEventListener('input', () => {
            filterStudents();
        });

        document.getElementById('teacherSearch').addEventListener('input', () => {
            filterTeachers();
        });

        // 初始加载学生数据
        loadStudents();
    });

    // 加载学生数据
    async function loadStudents() {
        const studentsBody = document.getElementById('studentsBody');
        studentsBody.innerHTML = `
        <tr class="text-center">
            <td colspan="6" class="px-6 py-12 text-gray-500">
                <i class="fa fa-spinner fa-spin text-2xl mb-2"></i>
                <p>加载中...</p>
            </td>
        </tr>
    `;
        try {
            const response = await fetch('/api/students');
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            originalStudents = await response.json();
            studentsBody.innerHTML = '';
            originalStudents.forEach(student => {
                const row = document.createElement('tr');
                row.className = 'hover:bg-gray-50 transition-colors duration-150';
                row.innerHTML = `
                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${student.id}</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${student.name}</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${student.age}</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${student.sex}</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${student.grade}</td>
                <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                    <button onclick="editStudent('${student.id}')" class="text-indigo-600 hover:text-indigo-900 mr-3">
                        <i class="fa fa-pencil"></i> 编辑
                    </button>
                    <button onclick="confirmDelete('student', '${student.id}', '${student.name}')" class="text-red-600 hover:text-red-900">
                        <i class="fa fa-trash"></i> 删除
                    </button>
                </td>
            `;
                studentsBody.appendChild(row);
            });
        } catch (error) {
            studentsBody.innerHTML = `
            <tr class="text-center">
                <td colspan="6" class="px-6 py-12 text-gray-500">
                    <i class="fa fa-exclamation-triangle text-2xl mb-2"></i>
                    <p>加载学生数据失败: ${error.message}</p>
                </td>
            </tr>
        `;
        }
    }

    // 加载教师数据
    async function loadTeachers() {
        const teachersBody = document.getElementById('teachersBody');
        teachersBody.innerHTML = `
        <tr class="text-center">
            <td colspan="6" class="px-6 py-12 text-gray-500">
                <i class="fa fa-spinner fa-spin text-2xl mb-2"></i>
                <p>加载中...</p>
            </td>
        </tr>
    `;
        try {
            const response = await fetch('/api/teachers');
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            originalTeachers = await response.json();
            teachersBody.innerHTML = '';
            originalTeachers.forEach(teacher => {
                const row = document.createElement('tr');
                row.className = 'hover:bg-gray-50 transition-colors duration-150';
                row.innerHTML = `
                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${teacher.id}</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${teacher.name}</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${teacher.age}</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${teacher.sex}</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${teacher.teaching}</td>
                <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                    <button onclick="editTeacher('${teacher.id}')" class="text-indigo-600 hover:text-indigo-900 mr-3">
                        <i class="fa fa-pencil"></i> 编辑
                    </button>
                    <button onclick="confirmDelete('teacher', '${teacher.id}', '${teacher.name}')" class="text-red-600 hover:text-red-900">
                        <i class="fa fa-trash"></i> 删除
                    </button>
                </td>
            `;
                teachersBody.appendChild(row);
            });
        } catch (error) {
            teachersBody.innerHTML = `
            <tr class="text-center">
                <td colspan="6" class="px-6 py-12 text-gray-500">
                    <i class="fa fa-exclamation-triangle text-2xl mb-2"></i>
                    <p>加载教师数据失败: ${error.message}</p>
                </td>
            </tr>
        `;
        }
    }

    // 模拟数据 - 班级
    const mockClasses = [
        {id: 'C2025001', name: '一年级一班'},
        {id: 'C2025002', name: '一年级二班'}
    ];

    let originalClasses = [...mockClasses];

    // DOM 加载完成后执行

    document.getElementById('classesTab').addEventListener('click', () => {
        // 隐藏学生和教师模块
        document.getElementById('studentsSection').classList.add('hidden');
        document.getElementById('teachersSection').classList.add('hidden');
        // 显示班级模块并更新样式
        document.getElementById('classesTab').classList.add('text-info', 'border-b-2', 'border-info');
        document.getElementById('classesTab').classList.remove('text-gray-500');
        document.getElementById('classesSection').classList.remove('hidden');
        loadClasses();
    });
    document.addEventListener('DOMContentLoaded', () => {
        // 初始化选项卡切换
        document.getElementById('studentsTab').addEventListener('click', () => {
            // 原有的学生选项卡点击逻辑
        });

        document.getElementById('teachersTab').addEventListener('click', () => {
            // 原有的教师选项卡点击逻辑
        });

        document.getElementById('classesTab').addEventListener('click', () => {
            document.getElementById('classesTab').classList.add('text-info', 'border-b-2', 'border-info');
            document.getElementById('classesTab').classList.remove('text-gray-500');
            document.getElementById('studentsTab').classList.remove('text-primary', 'border-b-2', 'border-primary');
            document.getElementById('studentsTab').classList.add('text-gray-500');
            document.getElementById('teachersTab').classList.remove('text-secondary', 'border-b-2', 'border-secondary');
            document.getElementById('teachersTab').classList.add('text-gray-500');
            document.getElementById('classesSection').classList.remove('hidden');
            document.getElementById('studentsSection').classList.add('hidden');
            document.getElementById('teachersSection').classList.add('hidden');

            // 加载班级数据
            loadClasses();
        });

        // 初始化模态框事件
        document.getElementById('addClassBtn').addEventListener('click', () => {
            document.getElementById('addClassModal').classList.remove('hidden');
            document.getElementById('addClassForm').reset();
        });

        document.getElementById('closeClassModal').addEventListener('click', () => {
            document.getElementById('addClassModal').classList.add('hidden');
        });

        document.getElementById('cancelAddClass').addEventListener('click', () => {
            document.getElementById('addClassModal').classList.add('hidden');
        });

        document.getElementById('closeEditClassModal').addEventListener('click', () => {
            document.getElementById('editClassModal').classList.add('hidden');
        });

        document.getElementById('cancelEditClass').addEventListener('click', () => {
            document.getElementById('editClassModal').classList.add('hidden');
        });

        // 初始化表单提交事件
        document.getElementById('addClassForm').addEventListener('submit', (e) => {
            e.preventDefault();
            addClass();
        });

        document.getElementById('editClassForm').addEventListener('submit', (e) => {
            e.preventDefault();
            updateClass();
        });

        // 初始化刷新按钮
        document.getElementById('refreshClasses').addEventListener('click', loadClasses);

        // 初始化搜索功能
        document.getElementById('classSearch').addEventListener('input', () => {
            filterClasses();
        });

        // 初始加载学生数据
        loadStudents();
    });

    function loadClasses() {
        const classesBody = document.getElementById('classesBody');
        classesBody.innerHTML = `
        <tr class="text-center">
            <td colspan="3" class="px-6 py-12 text-gray-500">
                <i class="fa fa-spinner fa-spin text-2xl mb-2"></i>
                <p>加载中...</p>
            </td>
        </tr>
    `;

        fetch('/api/classes')
            .then(response => {
                console.log('Response status:', response.status);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                console.log('Received data:', data);
                originalClasses = data;
                classesBody.innerHTML = '';
                data.forEach(classInfo => {
                    const row = document.createElement('tr');
                    row.className = 'hover:bg-gray-50 transition-colors duration-150';
                    row.innerHTML = `
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${classInfo.id}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${classInfo.name}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                        <button onclick="editClass('${classInfo.id}')" class="text-indigo-600 hover:text-indigo-900 mr-3">
                            <i class="fa fa-pencil"></i> 编辑
                        </button>
                        <button onclick="confirmDeleteClass('${classInfo.id}', '${classInfo.name}')" class="text-red-600 hover:text-red-900">
                            <i class="fa fa-trash"></i> 删除
                        </button>
                    </td>
                `;
                    classesBody.appendChild(row);
                });
            })
            .catch(error => {
                console.error('Error loading classes:', error);
                classesBody.innerHTML = `
                <tr class="text-center">
                    <td colspan="3" class="px-6 py-12 text-gray-500">
                        <i class="fa fa-exclamation-triangle text-2xl mb-2"></i>
                        <p>加载班级数据失败: ${error.message}</p>
                    </td>
                </tr>
            `;
            });
    }

    // 编辑班级
    function editClass(id, name) {
        // 直接使用传递的ID和名称，避免从originalClasses查找
        console.log('编辑班级参数 - ID:', id, '名称:', name);

        // 参数校验：若name为空，尝试从originalClasses中获取
        if (!name) {
            const classInfo = originalClasses.find(cls => cls.id === id);
            name = classInfo?.name || '';
            console.warn('从originalClasses中获取名称:', name);
        }

        document.getElementById('editClassId').value = id;
        document.getElementById('editClassName').value = name;
        document.getElementById('editClassModal').classList.remove('hidden');
    }

    // 更新班级
    function updateClass() {
        const id = document.getElementById('editClassId').value;
        const name = document.getElementById('editClassName').value;

        const updatedClass = {id, name};
        console.log('Updating class:', updatedClass);

        fetch(`/api/classes/${id}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(updatedClass)
        })
            .then(response => {
                console.log('Update class response status:', response.status);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                showNotification('success', '成功', '班级更新成功');
                document.getElementById('editClassModal').classList.add('hidden');
                loadClasses();
            })
            .catch(error => {
                console.error('Error updating class:', error);
                showNotification('error', '失败', '班级更新失败: ' + error.message);
            });
    }


    // 确认删除班级
    function confirmDeleteClass(id, name) {
        currentEntityType = 'class';
        currentClassId = id;
        console.log('确认删除班级，ID:', currentClassId); // 输出 ID 值
        document.getElementById('deleteMessage').textContent = `你确定要删除班级 "${name}" 吗？此操作不可撤销。`;
        document.getElementById('confirmDeleteModal').classList.remove('hidden');
    }

    // 删除班级
    function deleteClass() {
        if (!currentClassId) {
            console.log('currentClassId 未定义');
            return;
        }
        console.log('开始删除班级，ID:', currentClassId); // 输出 ID 值

        fetch(`/api/classes/${currentClassId}`, {
            method: 'DELETE'
        })
            .then(response => {
                console.log('删除班级响应状态码:', response.status);
                if (response.ok) {
                    showNotification('success', '成功', '班级删除成功');
                    originalClasses = originalClasses.filter(classInfo => classInfo.id !== currentClassId);
                    loadClasses();
                    document.getElementById('confirmDeleteModal').classList.add('hidden');
                } else {
                    showNotification('error', '失败', '班级删除失败');
                }
            })
            .catch(error => {
                showNotification('error', '失败', '班级删除失败: ' + error.message);
                console.error('删除班级出错:', error);
            });
    }

    // 搜索班级
    function filterClasses() {
        const searchTerm = document.getElementById('classSearch').value.toLowerCase();

        if (!searchTerm) {
            loadClasses();
            return;
        }

        const filteredClasses = originalClasses.filter(classInfo =>
            classInfo.id.toLowerCase().includes(searchTerm) ||
            classInfo.name.toLowerCase().includes(searchTerm)
        );

        const classesBody = document.getElementById('classesBody');

        if (filteredClasses.length === 0) {
            classesBody.innerHTML = `
            <tr class="text-center">
                <td colspan="3" class="px-6 py-12 text-gray-500">
                    <i class="fa fa-search text-2xl mb-2"></i>
                    <p>未找到匹配的班级</p>
                </td>
            </tr>
        `;
            return;
        }

        classesBody.innerHTML = '';
        filteredClasses.forEach(classInfo => {
            const row = document.createElement('tr');
            row.className = 'hover:bg-gray-50 transition-colors duration-150';
            row.innerHTML = `
            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${classInfo.id}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${classInfo.name}</td>
            <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
            <button onclick="editClass('${classInfo.id}', '${classInfo.name}')" class="text-indigo-600 hover:text-indigo-900 mr-3">
                <i class="fa fa-pencil"></i> 编辑
            </button>
                <button onclick="confirmDeleteClass('${classInfo.id}', '${classInfo.name}')" class="text-red-600 hover:text-red-900">
                <i class="fa fa-trash"></i> 删除
                </button>
            </td>
        `;
            classesBody.appendChild(row);
        });
    }

    // 添加学生
    function addStudent() {
        const id = document.getElementById('studentId').value;
        const name = document.getElementById('studentName').value;
        const age = parseInt(document.getElementById('studentAge').value);
        const sex = document.getElementById('studentSex').value;
        const grade = parseFloat(document.getElementById('studentGrade').value);

        // 发送 POST 请求到后端
        fetch('/api/students', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({id, name, age, sex, grade})
        })
            .then(response => response.json())
            .then(data => {
                showNotification('success', '成功', '学生添加成功');
                document.getElementById('addStudentModal').classList.add('hidden');
                document.getElementById('addStudentForm').reset();
                loadStudents();
            })
            .catch(error => {
                showNotification('error', '失败', '学生添加失败，请稍后重试');
                console.error('添加学生失败:', error);
            });
    }

    // 添加教师
    function addTeacher() {
        const id = document.getElementById('teacherId').value;
        const name = document.getElementById('teacherName').value;
        const age = parseInt(document.getElementById('teacherAge').value);
        const sex = document.getElementById('teacherSex').value;
        const teaching = document.getElementById('teacherTeaching').value;

        // 发送 POST 请求到后端
        fetch('/api/teachers', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({id, name, age, sex, teaching})
        })
            .then(response => response.json())
            .then(data => {
                showNotification('success', '成功', '教师添加成功');
                document.getElementById('addTeacherModal').classList.add('hidden');
                document.getElementById('addTeacherForm').reset();
                loadTeachers();
            })
            .catch(error => {
                showNotification('error', '失败', '教师添加失败，请稍后重试');
                console.error('添加教师失败:', error);
            });
    }

    // 编辑学生
    function editStudent(id) {
        currentStudentId = id;
        console.log('originalStudents:', originalStudents); // 添加日志输出

        const student = originalStudents.find(student => student.id === id);
        if (!student) {
            showNotification('error', '失败', '未找到该学生');
            return;
        }

        document.getElementById('editStudentId').value = student.id;
        document.getElementById('editStudentName').value = student.name;
        document.getElementById('editStudentAge').value = student.age;
        document.getElementById('editStudentSex').value = student.sex;
        document.getElementById('editStudentGrade').value = student.grade;
        document.getElementById('editStudentModal').classList.remove('hidden');
    }

    // 编辑教师
    function editTeacher(id) {
        currentTeacherId = id;

        const teacher = originalTeachers.find(teacher => teacher.id === id);
        if (!teacher) {
            showNotification('error', '失败', '未找到该教师');
            return;
        }

        document.getElementById('editTeacherId').value = teacher.id;
        document.getElementById('editTeacherName').value = teacher.name;
        document.getElementById('editTeacherAge').value = teacher.age;
        document.getElementById('editTeacherSex').value = teacher.sex;
        document.getElementById('editTeacherTeaching').value = teacher.teaching;
        document.getElementById('editTeacherModal').classList.remove('hidden');
    }

    // 更新学生
    function updateStudent() {
        const id = document.getElementById('editStudentId').value;
        const name = document.getElementById('editStudentName').value;
        const age = parseInt(document.getElementById('editStudentAge').value);
        const sex = document.getElementById('editStudentSex').value;
        const grade = parseFloat(document.getElementById('editStudentGrade').value);

        // 发送 PUT 请求到后端
        fetch(`/api/students/${id}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({id, name, age, sex, grade})
        })
            .then(response => response.json())
            .then(data => {
                showNotification('success', '成功', '学生信息更新成功');
                document.getElementById('editStudentModal').classList.add('hidden');
                loadStudents();
            })
            .catch(error => {
                showNotification('error', '失败', '学生信息更新失败，请稍后重试');
                console.error('更新学生信息失败:', error);
            });
    }

    // 更新教师
    function updateTeacher() {
        const id = document.getElementById('editTeacherId').value;
        const name = document.getElementById('editTeacherName').value;
        const age = parseInt(document.getElementById('editTeacherAge').value);
        const sex = document.getElementById('editTeacherSex').value;
        const teaching = document.getElementById('editTeacherTeaching').value;

        // 发送 PUT 请求到后端
        fetch(`/api/teachers/${id}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({id, name, age, sex, teaching})
        })
            .then(response => response.json())
            .then(data => {
                showNotification('success', '成功', '教师信息更新成功');
                document.getElementById('editTeacherModal').classList.add('hidden');
                loadTeachers();
            })
            .catch(error => {
                showNotification('error', '失败', '教师信息更新失败，请稍后重试');
                console.error('更新教师信息失败:', error);
            });
    }

    // 确认删除
    function confirmDelete(entityType, id, name) {
        currentEntityType = entityType;
        if (entityType === 'student') {
            currentStudentId = id;
            document.getElementById('deleteMessage').textContent = `你确定要删除学生 "${name}" 吗？此操作不可撤销。`;
        } else if (entityType === 'teacher') {
            currentTeacherId = id;
            document.getElementById('deleteMessage').textContent = `你确定要删除教师 "${name}" 吗？此操作不可撤销。`;
        }
        document.getElementById('confirmDeleteModal').classList.remove('hidden');
    }

    // 删除学生
    function deleteStudent() {
        if (!currentStudentId) return;

        // 发送 DELETE 请求到后端
        fetch(`/api/students/${currentStudentId}`, {
            method: 'DELETE'
        })
            .then(response => {
                if (response.ok) {
                    showNotification('success', '成功', '学生删除成功');
                    loadStudents();
                } else {
                    showNotification('error', '失败', '学生删除失败，请稍后重试');
                    console.error('删除学生失败:', response.statusText);
                }
            })
            .catch(error => {
                showNotification('error', '失败', '学生删除失败，请稍后重试');
                console.error('删除学生失败:', error);
            });

        document.getElementById('confirmDeleteModal').classList.add('hidden');
    }

    // 删除教师
    function deleteTeacher() {
        if (!currentTeacherId) return;

        // 发送 DELETE 请求到后端
        fetch(`/api/teachers/${currentTeacherId}`, {
            method: 'DELETE'
        })
            .then(response => {
                if (response.ok) {
                    showNotification('success', '成功', '教师删除成功');
                    loadTeachers();
                } else {
                    showNotification('error', '失败', '教师删除失败，请稍后重试');
                    console.error('删除教师失败:', response.statusText);
                }
            })
            .catch(error => {
                showNotification('error', '失败', '教师删除失败，请稍后重试');
                console.error('删除教师失败:', error);
            });

        document.getElementById('confirmDeleteModal').classList.add('hidden');
    }

    // 搜索学生
    function filterStudents() {
        const searchTerm = document.getElementById('studentSearch').value.toLowerCase();

        if (!searchTerm) {
            loadStudents();
            return;
        }

        const filteredStudents = originalStudents.filter(student =>
            student.id.toLowerCase().includes(searchTerm) ||
            student.name.toLowerCase().includes(searchTerm) ||
            student.sex.toLowerCase().includes(searchTerm)
        );

        const studentsBody = document.getElementById('studentsBody');

        if (filteredStudents.length === 0) {
            studentsBody.innerHTML = `
                    <tr class="text-center">
                        <td colspan="6" class="px-6 py-12 text-gray-500">
                            <i class="fa fa-search text-2xl mb-2"></i>
                            <p>未找到匹配的学生</p>
                        </td>
                    </tr>
                `;
            return;
        }

        studentsBody.innerHTML = '';
        filteredStudents.forEach(student => {
            const row = document.createElement('tr');
            row.className = 'hover:bg-gray-50 transition-colors duration-150';
            row.innerHTML = `
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${student.id}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${student.name}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${student.age}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${student.sex}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${student.grade}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                        <button onclick="editStudent('${student.id}')" class="text-indigo-600 hover:text-indigo-900 mr-3">
                            <i class="fa fa-pencil"></i> 编辑
                        </button>
                        <button onclick="confirmDelete('student', '${student.id}', '${student.name}')" class="text-red-600 hover:text-red-900">
                            <i class="fa fa-trash"></i> 删除
                        </button>
                    </td>
                `;
            studentsBody.appendChild(row);
        });
    }

    // 搜索教师
    function filterTeachers() {
        const searchTerm = document.getElementById('teacherSearch').value.toLowerCase();

        if (!searchTerm) {
            loadTeachers();
            return;
        }

        const filteredTeachers = originalTeachers.filter(teacher =>
            teacher.id.toLowerCase().includes(searchTerm) ||
            teacher.name.toLowerCase().includes(searchTerm) ||
            teacher.sex.toLowerCase().includes(searchTerm) ||
            teacher.teaching.toLowerCase().includes(searchTerm)
        );

        const teachersBody = document.getElementById('teachersBody');

        if (filteredTeachers.length === 0) {
            teachersBody.innerHTML = `
                    <tr class="text-center">
                        <td colspan="6" class="px-6 py-12 text-gray-500">
                            <i class="fa fa-search text-2xl mb-2"></i>
                            <p>未找到匹配的教师</p>
                        </td>
                    </tr>
                `;
            return;
        }

        teachersBody.innerHTML = '';
        filteredTeachers.forEach(teacher => {
            const row = document.createElement('tr');
            row.className = 'hover:bg-gray-50 transition-colors duration-150';
            row.innerHTML = `
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${teacher.id}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${teacher.name}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${teacher.age}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${teacher.sex}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${teacher.teaching}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                        <button onclick="editTeacher('${teacher.id}')" class="text-indigo-600 hover:text-indigo-900 mr-3">
                            <i class="fa fa-pencil"></i> 编辑
                        </button>
                        <button onclick="confirmDelete('teacher', '${teacher.id}', '${teacher.name}')" class="text-red-600 hover:text-red-900">
                            <i class="fa fa-trash"></i> 删除
                        </button>
                    </td>
                `;
            teachersBody.appendChild(row);
        });
    }

    // 显示通知
    function showNotification(type, title, message) {
        const notification = document.getElementById('notification');
        const notificationHeader = document.getElementById('notificationHeader');
        const notificationTitle = document.getElementById('notificationTitle');
        const notificationMessage = document.getElementById('notificationMessage');

        // 设置通知样式和内容
        if (type === 'success') {
            notificationHeader.className = 'p-3 bg-green-500 text-white flex justify-between items-center';
        } else if (type === 'error') {
            notificationHeader.className = 'p-3 bg-red-500 text-white flex justify-between items-center';
        } else if (type === 'warning') {
            notificationHeader.className = 'p-3 bg-yellow-500 text-white flex justify-between items-center';
        } else {
            notificationHeader.className = 'p-3 bg-primary text-white flex justify-between items-center';
        }

        notificationTitle.textContent = title;
        notificationMessage.textContent = message;

        // 显示通知
        notification.classList.remove('translate-x-full');
        notification.style.right = '1rem';

        // 5 秒后自动关闭
        setTimeout(() => {
            notification.classList.add('translate-x-full');
            notification.style.right = '-100%';
        }, 5000);
    }

    // 关闭通知
    document.getElementById('closeNotification').addEventListener('click', () => {
        const notification = document.getElementById('notification');
        notification.classList.add('translate-x-full');
        notification.style.right = '-100%';
    });
</script>
</body>
</html>